const fs = require('fs')
const cwd = process.cwd()
const ejs = require('ejs')
const ora = require('ora')
const path = require('path')
const chalk = require('chalk')
const inquirer = require('inquirer')
const { clone } = require('dl-files')
const { messageBox } = require('./tools')

const spinner = ora()
spinner.color = 'green'
const basename = path.basename(cwd)

let EJSDATA = null

const configPrompts = [
  {
    type: 'input',
    name: 'projectName',
    message: `请输入项目名称：`,
    validate(val) {
      if (!val) return chalk.red('请输入项目名称')
      else if (!/^[a-zA-Z0-9_-]+$/.test(val)) return chalk.red('请输入规范的项目名称。可以是英文、数字、下划线或减号')
      else return true
    }
  },
  {
    type: 'input',
    name: 'title',
    message: `请输入网站标题：`,
    default: 'my-blog'
  },
  {
    type: 'input',
    name: 'author',
    message: `请输入站长名称：`
  },
  {
    type: 'input',
    name: 'subtitle',
    message: `请输入网站副标题：`
  },
  {
    type: 'input',
    name: 'description',
    message: `请输入网站描述：`
  },
  {
    type: 'input',
    name: 'keywords',
    message: `请输入网站关键字，以逗号分隔：`
  },
  {
    type: 'input',
    name: 'theme',
    message: `请输入网站主题：`,
    default: 'daiter'
  },
  {
    type: 'confirm',
    name: 'loadNpm',
    message: `是否在安装网页模板后自动下载依赖：`,
    default: true
  }
]

const downFiles = () => {
  messageBox.info('安装网页模板...')
  return clone({
    input: path.join(__dirname, '../template'),
    output: cwd,
    fileName: EJSDATA.projectName,
    handleCopy(input, output) {
      spinner.start()
      return new Promise(resolve => {
        // 通过模板引擎读取文件内容，并写入上下文
        const basename = path.basename(input)
        if (basename.startsWith('.')) {
          const readable = fs.createReadStream(input)
          const writable = fs.createWriteStream(output) 
          readable.pipe(writable)
          readable.on('close', () => {
            spinner.succeed(' -- ' + input)
            resolve()
          })
        } else {
          ejs.renderFile(input, EJSDATA, (err, result) => {
            if (err) throw err
            // 生成文件
            fs.writeFileSync(output, result)
            resolve()
          })
        }
      })
    }
  })
}

const writeJson = () => {
  const packageJson = require('../config/package.json')
  return new Promise(resolve => {
    packageJson.name = EJSDATA.projectName
    packageJson.author = EJSDATA.author
    fs.writeFile(
      path.join(cwd, `./${EJSDATA.projectName}/package.json`),
      JSON.stringify(packageJson, null, '\t'),
      (err, res) => {
        if (err) throw err
        resolve()
      }
    )
  })
}

inquirer
  .prompt(configPrompts)
  .then(answer => {
    EJSDATA = answer
    EJSDATA.htmlWebpackPluginStr = '<%= htmlWebpackPlugin.options.title %>'
  })
  .then(downFiles)
  .then(writeJson)
  .then(() => {
    messageBox.success('网页模板已成功安装')
    if (!EJSDATA.loadNpm) return

    messageBox.info('下载项目依赖...')
    const exec = require('child_process').execSync
    exec('npm install', {
      stdio: 'inherit',
      cwd: path.join(cwd, './', EJSDATA.projectName)
    })
  })